<script setup>
import { reactive, ref } from "vue";
import { onMounted } from "vue";
import {
  selectAllUser,
  deleteUser,
  getClassInfo,
  selectClass,
  amendClass
} from "@/api/common/work/CourseUp";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { useTokenStore } from "@/store/token.js";
const token = useTokenStore();
const route = useRoute();
import { get } from "jquery";
import { Delete } from "@element-plus/icons-vue";
// 屏幕宽度
const windowWidth = ref(0);
// 屏幕高度
const windowHeight = ref(0);
var classId = ref(0);
const classInfo = ref({});
// 定义 checkList
const checkList = ref([]);

// 生命周期
onMounted(() => {
  getWindowResize();
  window.addEventListener("resize", getWindowResize);
  //console.log(token);
  classId.value = route.query.classId;
  getClass();
  getAllUser();
});

const getClass = async () => {
  let res = await getClassInfo(classId.value);
  classInfo.value = res.data;
};

// 获取屏幕尺寸
const getWindowResize = function () {
  windowWidth.value = window.innerWidth;
  windowHeight.value = window.innerHeight;
};

const handleClick = () => {
  //console.log("click");
};

const getAllUser = async () => {
  let res = await selectAllUser(classId.value);
  if (res.data && res.data.length > 0) {
    res.data.forEach((element) => {
      if (element.userSex == 0) {
        element.userSex = "男";
      } else {
        element.userSex = "女";
      }
      tableData.push(element);
    });
  }
};

const tableData = reactive([]);

function showFileChooser() {
  const input = document.createElement("input");
  input.type = "file";
  input.accept =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  input.click();
  input.addEventListener("change", async function () {
    const file = this.files[0];
    if (!file) return;
    const formData = new FormData();
    formData.append("file", file);
    formData.append("classId", classId.value);
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "/api/excel/importData", true); // 假设你的后端API位于"/upload"
    xhr.setRequestHeader("Authorization", token.token);
    // 设置进度条更新函数
    xhr.upload.addEventListener("progress", function (event) {});
    xhr.onload = function () {
      if (xhr.status === 200) {
        //console.log("File uploaded successfully.");
        const response = JSON.parse(xhr.responseText);
        //console.log(response);
        if (response.code == 333) {
          ElMessage({
            type: "warning",
            message: response.msg,
          });
        }
        setTimeout(() => {
          location.reload();
        }, 2000);
      } else {
        console.error("Error uploading file.");
      }
    };
    xhr.send(formData);
  });
}

const open = (userId) => {
  ElMessageBox.confirm("是否将该学生移除当前班级并删除学生", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "返回",
    type: "warning",
  })
    .then(async () => {
      await deleteUser(userId);
      location.reload();
      ElMessage({
        type: "success",
        message: "移除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "放弃移除",
      });
    });
};

//选择删除学生
const handleSelectionChange = (val) => {
  checkList.value = val;
};

const qk = async () => {
  if (checkList.value.length === 0) {
    ElMessage({
      type: "info",
      message: "请选择要删除的学生",
    });
    return;
  }

  ElMessageBox.confirm("是否将选中的学生移除当前班级并删除学生", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "返回",
    type: "warning",
  })
    .then(async () => {
      for (const user of checkList.value) {
        await deleteUser(user.userId);
      }
      location.reload();
      ElMessage({
        type: "success",
        message: "移除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "放弃移除",
      });
    });
};


// 对话框显示状态
const dialogVisible01 = ref(false);
// 班级选项列表
const classOptions = ref([]);
// 选中的班级ID
const selectedClassId = ref('');
//存放选中的用户id
const classuserId = ref('');

const change01 = async (userId) => {
  //存放用户id
  classuserId.value = userId;
  //查询所拥有的班级
  let shuju = await selectClass();
  classOptions.value = shuju.data.map(item => ({
    value: item.classId,
    label: item.className
  }));
  // 显示对话框
  dialogVisible01.value = true;
};

const handleClose = (done) => {
  dialogVisible01.value = false;
  selectedClassId.value = ''; // 清空选中的班级ID
  done();
};

const part=ref({});

const confirmChange = async () => {
  if (selectedClassId.value) {
    //console.log(`用户 ${classuserId.value} 将被转到班级 ${selectedClassId.value}`);
    part.value.classId = selectedClassId.value;
    part.value.userId = classuserId.value;
    try {
      let shuju = await amendClass(part.value);
      //console.log(shuju);
      if (shuju.data == 1) {
        ElMessage.success("转班成功!");
        // 刷新当前页面
        window.location.reload();
      } else {
        ElMessage.error("转班失败!");
      }
    } catch (error) {
      console.error("转班请求失败:", error);
      ElMessage.error("转班失败!");
    }
    selectedClassId.value = '';
    dialogVisible01.value = false;
  } else {
    ElMessage({
      type: 'warning',
      message: '请选择一个班级'
    });
  }
};

</script>
<template>
  <div class="resourceTop">
    <div class="top">
      <div class="anniu">
        <div class="logo">
          <img src="../../../assets/img/kechengziyuan.png" alt="" />
        </div>
        <div>
          <el-button class="qk" @click="qk">删除</el-button>
        </div>
      </div>

      <div class="text">
        <!-- <p class="title">{{ classInfo.className }}</p> -->
        <!-- <p>
          <span
            >创建者：{{ classInfo.nickName }} &nbsp;&nbsp;&nbsp;学员数量：{{
              tableData.length
            }}</span
          >
        </p> -->
      </div>
      <div class="add">
        <button @click="showFileChooser()">批量导入学员信息</button>
        <a
          href="https://saas-os.oss-cn-beijing.aliyuncs.com/student.xlsx"
          title="点击下载学生信息模板"
        >
          <button
            style="
              width: 150px;
              height: 40px;
              background-color: #f4523b;
              border: none;
              color: #fff;
              font-size: 16px;
              border-radius: 5px;
              cursor: pointer;
              margin-left: 20px;
            "
          >
            下载学生信息模板
          </button>
        </a>
      </div>
    </div>
  </div>
  <div
    class="bottom"
    :style="{
      height: windowHeight - 180 + 'px',
      width: windowWidth - 80 + 'px',
    }"
  >
    <el-table
      :data="tableData"
      style="width: 94%; margin: 0 auto"
      @selection-change="handleSelectionChange"
    >
      <!-- 添加多选列 -->
      <el-table-column type="selection" width="55" />
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          label="Option A"
          :value="tableData.userId"
          style="border: 1px solid red"
        />
      </el-checkbox-group>
      <el-table-column fixed prop="nickName" label="名字" width="150" />
      <el-table-column prop="userName" label="账号" width="200" />

      <el-table-column prop="userEmail" label="邮箱" width="240" />
      <el-table-column prop="userCard" label="身份证" width="250" />
      <el-table-column prop="userSex" label="性别" width="200" />
      <el-table-column prop="userPhone" label="手机号" width="200" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="tableData">
          <el-button
            link
            type="primary"
            size="small"
            @click="open(tableData.row.userId)"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            size="small"
            @click="change01(tableData.row.userId)"
            >转班</el-button>

              <!-- 弹出选择班级的对话框 -->
                <el-dialog
                  v-model="dialogVisible01"
                  title="转班"
                  width="500"
                  :modal="false"
                  :before-close="handleClose"
                >
                  <el-select v-model="selectedClassId" placeholder="请选择班级">
                    <el-option
                      v-for="option in classOptions"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-select>
                  <template #footer>
                    <div class="dialog-footer">
                      <el-button @click="handleClose">取消</el-button>
                      <el-button type="primary" @click="confirmChange">确认</el-button>
                    </div>
                  </template>
                </el-dialog>

        </template>        
      </el-table-column>

    </el-table>
  </div>
</template>
<style scoped>
.top {
  position: relative;

}
.anniu{
  width: 150px;
  height: 100px;
  margin-left: 20px;
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.qk {
  width: 80px;
  height: 30px;
  font-size: 16px;
  transition: background-color 0.3s, border-color 0.3s;
  color: #fff;
  background-color: #f97705;
  margin-top: 10px;
}
.qk:hover {
  background-color: var(--el-button-hover-bg-color); /* 使用主题变量 */
  border-color: var(--el-button-hover-bg-color); /* 使用主题变量 */
}
.qk:hover {
  background-color: #f9a537;
  border-color: #fbcb5b;
}

.qk .el-icon-delete {
  margin-right: 5px;
}

.bottom {
  background-color: #f8f8f8;
}

.resourceTop {
  width: 100%;
  height: 120px;
  background-color: #f5f5f5;
}

.resourceTop .top {
  width: 100%;
  height: 100px;
  display: flex;
  align-items: center;
  justify-items: center;
}

.resourceTop .top .logo {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ff6b0f;
}

.resourceTop .top .logo img {
  width: 45px;
  height: 45px;
  padding: 12px;
  cursor: pointer;
}

.resourceTop .top .text {
  width: 350px;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-left: 20px;
}

.resourceTop .top .text .title {
  font-size: 22px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 10px;
}

.resourceTop .top .text p span {
  color: rgba(0, 0, 0, 0.45);
}

.resourceTop .top .text p a {
  color: #f4523b;
}

.resourceTop .top .add {
  margin-left: 550px;
}

.resourceTop .top .add button {
  width: 150px;
  height: 40px;
  background-color: #f4523b;
  border: none;
  color: #fff;
  font-size: 16px;
  border-radius: 5px;
  cursor: pointer;
}

.resourceTop .top .select {
  margin-left: 10px;
  display: flex;
}

.resourceTop .top .select select {
  width: 100px;
  height: 40px;
  margin-right: 10px;
  font-size: 16px;
  padding-left: 20px;
  border: 1px solid #d6d6d6;
  border-radius: 5px;
}

.resourceTop .top .select select option {
  color: #676767;
  cursor: pointer;
}

.resourceTop .top .select button {
  width: 100px;
  height: 40px;
  border: 1px solid #d6d6d6;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  background-color: #fff;
}

.resourceTop .top .select button:hover {
  background-color: #f9e3e3;
}

.resourceTop .top .select select:hover {
  color: #f4523b;
  cursor: pointer;
}

.resourceTop .top .select select:focus {
  border: 1px solid #d6d6d6;
  outline: none;
}

.resourceTop .top .search {
  margin-left: 15px;
  display: flex;
  border-radius: 2px;
  background-color: #fafafa;
  justify-items: center;
  align-items: center;

  border: 1px solid #d6d6d6;
}

.resourceTop .top .search:hover {
  border: 1px solid #f4523b;
}

.resourceTop .top .search .sousuo {
  width: 40px;
  height: 40px;
  padding-left: 5px;
  padding-top: 5px;
  border-right: none;
  background-color: #fff;
}

.resourceTop .top .search .sousuo img {
  width: 80%;
}

.resourceTop .top .search input {
  width: 320px;
  height: 40px;
  border: none;
  background-color: #fff;
  border-left: none;
}

.resourceTop .top .search input:focus {
  outline: none;
}

.resourceTop .top .search:hover .sousuo {
  border-right: none;
}

.resourceTop .top .search:hover input {
  border-left: none;
}

.resourceTop .bottom {
  display: flex;
  height: 50px;
}

.resourceTop .bottom .text {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 150px;
  height: 50px;
  font-size: 20px;
  margin-left: 10px;
  border: none;
  cursor: pointer;
}
</style>
